package com.woniuxy.qiantai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.qiantai.entity.Comment;
import com.woniuxy.qiantai.entity.Shop;
import com.woniuxy.qiantai.entity.Type;
import com.woniuxy.qiantai.mapper.CommentMapper;
import com.woniuxy.qiantai.mapper.OrderMapper;
import com.woniuxy.qiantai.mapper.ShopMapper;
import com.woniuxy.qiantai.mapper.TypeMapper;
import com.woniuxy.qiantai.service.ShopAllService;
import com.woniuxy.qiantai.utils.List2PageUtils;
import com.woniuxy.qiantai.vo.ShopAll;
import com.woniuxy.qiantai.vo.ShopAndTypeES;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ShopAllServiceImpl implements ShopAllService {
    @Autowired
    ShopMapper shopMapper;
    @Autowired
    TypeMapper typeMapper;
    @Autowired
    CommentMapper commentMapper;
    @Autowired
    OrderMapper orderMapper;

    @Autowired
    ElasticsearchRepository elasticsearchRepository;

    List2PageUtils list2PageUtils=new List2PageUtils();
    @Override
    public PageInfo<ShopAll> shoppAll(Integer currentPage, Integer pageSize) {

        List<Shop> shopList = shopMapper.selectList(null);
        List<ShopAll> shopAllList = shopList2ShopAllList(shopList);
        PageInfo<ShopAll> shopAllPageInfo = new PageInfo<>();
        List<ShopAll> shopAllToAddList = new ArrayList<>();
        shopAllPageInfo = list2PageUtils.pageInfo(shopAllList, shopAllToAddList, shopAllPageInfo,
                currentPage, pageSize);
        return shopAllPageInfo;
    }

    @Override
    public PageInfo<ShopAll> selectShopAllByType(String typeName, Integer currentPage,
                                                 Integer pageSize) {
        PageHelper.startPage(currentPage, pageSize);
        List<Shop> shopList = shopMapper.selectShopByType(typeName);
        List<ShopAll> shopAllList = shopList2ShopAllList(shopList);
        List<ShopAll> shopAllListToAdd = new ArrayList<>();
        PageInfo<ShopAll> shopAllPageInfo = new PageInfo<>();
        shopAllPageInfo=list2PageUtils.pageInfo(shopAllList,shopAllListToAdd,shopAllPageInfo,
                currentPage,pageSize);
        return shopAllPageInfo;
    }
    @Override
    public PageInfo<ShopAll> searchShopAllByES(Integer currentPage, Integer pageSize,
                                         String keyword) {

        //构建查询条件
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();

        //query
        nativeSearchQueryBuilder.withQuery(QueryBuilders.multiMatchQuery(keyword, "name",
                "typeName", "detail")).addAggregation(
                AggregationBuilders.terms("shopIds").field("shopId"));

        AggregatedPage<ShopAndTypeES> aggPage =
                (AggregatedPage<ShopAndTypeES>) this.elasticsearchRepository.search(nativeSearchQueryBuilder.build());
        // 3、解析
        Terms agg = (Terms) aggPage.getAggregation("shopIds");
        List<? extends Terms.Bucket> buckets = agg.getBuckets();
        List<Shop> shopList = new ArrayList<>();
        // 3.3、遍历
        for (Terms.Bucket bucket : buckets) {
            // 3.4、获取桶中的key，即品牌名称
            //  System.out.println((Integer)bucket.getKeyAsNumber().intValue());
            // 3.5、获取桶中的文档数量
            //System.out.println(bucket.getDocCount());
            Shop shop = new Shop();
            shop.setId(bucket.getKeyAsNumber().intValue());
            shopList.add(shop);
        }
        for (Shop shop : shopList) {
            int currentIndex = shopList.indexOf(shop);
            shop = shopMapper.selectById(shop.getId());
            shopList.set(currentIndex, shop);
        }

        PageInfo<ShopAll> shopAllPageInfo = new PageInfo<>();
        List<ShopAll> shopAllToAddList = new ArrayList<>();
        List<ShopAll> shopAllList = shopList2ShopAllList(shopList);

        return list2PageUtils.pageInfo(shopAllList, shopAllToAddList, shopAllPageInfo, currentPage,
                pageSize);
    }
    protected List<ShopAll> shopList2ShopAllList(List<Shop> shopList) {
        List<ShopAll> shopAllList = new ArrayList<>();
        for (Shop shop : shopList) {
            //存shop的基本属性
            ShopAll shopAll = new ShopAll();
            shopAll.setShop(shop);
            //存type的列表
            QueryWrapper qwType = new QueryWrapper();
            qwType.eq("shop_id", shop.getId());
            List<Type> typeList = typeMapper.selectList(qwType);
            shopAll.setType(typeList);
            //存评论的平均分
            QueryWrapper qwComment = new QueryWrapper();
            qwComment.select("ROUND(AVG(grade),1) grade");
            qwComment.eq("shop_id", shop.getId());
            Comment comment = commentMapper.selectOne(qwComment);
            if (comment == null) {
                comment = new Comment();
                comment.setGrade(4.0);
            }
            shopAll.setGrade(comment.getGrade());
            //计算人均消费
            Integer perCost = orderMapper.perCost(shop.getId());
            if (perCost == null){
                perCost = 20;
            }
            perCost = (int)Math.ceil(perCost/10)*10;
            shopAll.setPerCost(perCost);
            //存订单的数量
//            QueryWrapper qwOrder = new QueryWrapper<>();
//            qwOrder.eq("shop_id", shop.getId());
//            qwOrder.and(wrapper -> wrapper.eq("status", 6)
//                    .or().eq("status", 7)
//            );
            Integer count = orderMapper.countOrder(shop.getId());
            if (count == null) {
                count = 0;
            }
            shopAll.setCount(count);
            //完成，存到shopAll列表中
            shopAllList.add(shopAll);
        }
        return shopAllList;
    }
}
